//
//  ViewController.m
//  mobileverify
//
//  Created by Criss on 2017/12/25.
//  Copyright © 2017年 SONG. All rights reserved.
//

#import "ViewController.h"
#import <JRMFMobileVerify/JRMFMobileVerify.h>
#import <JYangToolKit/JYangToolKit.h>
#import <CommonCrypto/CommonDigest.h>


/**< 联通 */
#define APP_ID_CU   @"mobile"
#define APP_KEY_CU  @"mobile"

/**< 移动 */
#define APP_ID_CM   @"300011846577"
#define APP_KEY_CM  @"73FC7BBE073D02C7063B901B87C71D50"

/**< 电信 */
#define APP_ID_CT   @"8148610449"
#define APP_KEY_CT  @"3NAgAm2STx9GodmSE8vCOyrZpMKuyIWJ"

/**< 金融魔方 */
#define JRMFPartnerId @"jrmfauthtest"
#define JRMFSeckey    @"38ed9217-da84-4820-a4e0-f72df77250da"

@interface ViewController ()
{
    NSDateFormatter * _formatter;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化sdk
    JRMFInfoModel * model = [[JRMFInfoModel alloc]init];
    model.CM_APPID    = APP_ID_CM;
    model.CM_APPKEY   = APP_KEY_CM;
    model.CT_APPID    = APP_ID_CT;
    model.CT_APPKEY   = APP_KEY_CT;
    model.CU_APPID    = APP_ID_CU;
    model.CU_APPKEY   = APP_KEY_CU;
    model.JRMF_APPID  = JRMFPartnerId;
    model.JRMF_APPKEY = JRMFSeckey;
    [JRMFMobile instanceJRMFWith:model];
    
    
    _formatter = [[NSDateFormatter alloc]init];
    _formatter.dateFormat = @"YYYYMMddHHmmss";
}

/**
 验证手机号码
 */
- (IBAction)verfiyNum:(id)sender {
    
    /**< 获取Token */
    [JRMFMobile getDeviceToken:^(NSString *accessToken, JRMFMobileType operatorType, NSError *er) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (er) {
                NSLog(@"\n获取token错误\n####  %@",er);
                [self showAlertWithTitle:@"错误" des:er.description];
            }else{
                NSLog(@"\n获取token成功\n####  %@",accessToken);
                [self resuqestWith:accessToken withType:operatorType];
            }
        });
    }];
}

/**
 校验手机号码

 @param accessToken token
 @param type 当前手机号码类型 移动，电信，联通
 */
- (void)resuqestWith:(NSString *)accessToken withType:(JRMFMobileType)type
{
    if (self.phoneT.text.length != 11) {
        [self showAlertWithTitle:@"错误" des:@"手机号码有误"];
        return;
    }
    
    NSString * requestUrl = @"";
    NSString * mobileType = @"";
    
    // 请求接口
    switch (type) {
        case JRMFMobileTypeCT:
        {
            requestUrl = [NSString stringWithFormat:@"%@%@",@"https://yun-test2.jrmf360.com/",@"authenLogin/api/v1/ctcc/valiMobile.shtml"];
            mobileType = @"CT";
        }
            break;
        case JRMFMobileTypeCU:
        {
            requestUrl = [NSString stringWithFormat:@"%@%@",@"https://yun-test2.jrmf360.com/",@"authenLogin/api/v1/cucc/valiMobile.shtml"];
            mobileType = @"CU";
        }
            break;
        case JRMFMobileTypeCM:
        {
            requestUrl = [NSString stringWithFormat:@"%@%@",@"https://yun-test2.jrmf360.com/",@"authenLogin/api/v1/cmcc/valiMobile.shtml"];
            mobileType = @"CM";
        }
            break;
        default:
            break;
    }
    
    // 时间戳
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSString *timeString = [_formatter stringFromDate:date];
    
    NSDictionary * mdic = @{@"partnerId":JRMFPartnerId,
                            @"seckey":JRMFSeckey,
                            @"mobileToken":accessToken,
                            @"operatorType":mobileType,
                            @"mobileNo":self.phoneT.text,
                            @"clientType":@"30300",
                            @"timeStamp":timeString};
    
    
    // 数组排序后用 | 链接，MD5加密后作为sign value
    NSArray * keys = \
    [mdic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];
    }];
    NSMutableArray * signArr = [NSMutableArray arrayWithCapacity:0];
    for (NSString * key in keys) {
        [signArr addObject:[NSString stringWithFormat:@"%@:%@",key,mdic[key]]];
    }
    NSString * sign = [signArr componentsJoinedByString:@"|"];
    
    NSMutableDictionary * parameterDic = [NSMutableDictionary dictionaryWithDictionary:mdic];
    [parameterDic removeObjectForKey:@"seckey"];
    
    // 拼接参数
    NSMutableArray * parameterArr = [NSMutableArray arrayWithCapacity:0];
    for (NSString * key in parameterDic.allKeys) {
        [parameterArr addObject:[NSString stringWithFormat:@"%@=%@",key,parameterDic[key]]];
    }
    NSMutableString * patmStr = [[NSMutableString alloc]initWithString:[parameterArr componentsJoinedByString:@"&"]];
    [patmStr appendString:[NSString stringWithFormat:@"&%@=%@",@"sign",[[self md5:sign] lowercaseString]]];
    
    
    [JYangLib postGetRequestWithLink:requestUrl parameter:patmStr Success:^(NSURLSessionDataTask *task, NSDictionary *responseObj) {
        NSLog(@"%@",responseObj);
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([responseObj[@"respstat"] isEqualToString:@"0000"]) {
                
                switch ([responseObj[@"verfiyStatus"] intValue]) {
                    case 0:
                        [self showAlertWithTitle:@"成功" des:@"号码一致"];
                        break;
                    case 1:
                        [self showAlertWithTitle:@"成功" des:@"号码不一致"];
                        break;
                    case 2:
                        [self showAlertWithTitle:@"成功" des:@"无法判断"];
                        break;
                    default:
                        break;
                }
            }else{
                [self showAlertWithTitle:@"" des:[NSString stringWithFormat:@"%@",responseObj[@"respmsg"]]];
            }
        });
    } Fail:^(NSURLSessionDataTask *task, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showAlertWithTitle:@"错误" des:error.description];
        });
    }];
}
- (void)showAlertWithTitle:(NSString *)t des:(NSString *)des
{
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:t message:des delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alert show];
}

- (NSString *)md5:(NSString *)string{
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02X", digest[i]];
    }
    
    return result;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
